import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }
    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }
    }
    public void createHeap(){
        for(int parent=(this.usedSize-1-1)/2;parent>=0;parent--){
            shiftDown(parent,this.usedSize);
        }
    }

    public void shiftDown(int parent,int usedSize){
        int child =parent*2+1;
        while(child<usedSize){
            //如果孩子存在，找到左右孩子中较小的孩子，用child标记
            if (child + 1 < usedSize && elem[child] < elem[child+1]) {
                child=child+1;
            }
            if(elem[parent]>=elem[child]){
                break;
            }else{
                int tmp=elem[child];
                elem[child]=elem[parent];
                elem[parent]=tmp;

                parent=child;
                child=parent*2+1;
            }
        }
    }

    /**
     * 入堆：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            elem = Arrays.copyOf(elem, elem.length*2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private boolean isFull() {
        return usedSize == elem.length;
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(parent >= 0) {
            if (elem[parent] < elem[child]) {
                int tmp=elem[child];
                elem[child]=elem[parent];
                elem[parent]=tmp;
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }

    private boolean isEmpty(){
        return usedSize==0;
    }
    public void removeHeap(){
        if(isEmpty()){
            throw new RuntimeException("Heap is empty");
        }else{
            int child=usedSize-1;
            int tmp=elem[child];
            elem[child]=elem[0];
            elem[0]=tmp;
            usedSize--;
            shiftDown(0,usedSize);
        }
    }
}
